<template>
  <div class="tast-chapter">
    <div class="tast-score">
      <span>试卷总分</span>
      <p> {{ totalScore }} 分 (该值自动计算，无需填写)</p>
    </div>
    <div class="tast-chapter-wrap">
      <div class="chapter-left">
        <p>章节设置</p>
      </div>
      <div class="chapter-right">
        <div>
          <el-button
            type="primary"
            size="mini"
            @click="handleAddChapter()"
            icon="el-icon-plus"
            >增加章节</el-button
          >
        </div>
        <draggable
          class="draggable-chapter"
          v-model="testPaperChapterList"
          handle=".chapter-item-title"
        >
          <transition-group>
            <div
              class="chapter-item"
              v-for="(v, i) in testPaperChapterList"
              :key="v.mark"
            >
              <div class="chapter-item-title">
                <span class="item-txt">章节名称</span>
                <el-input
                  class="item-ipt"
                  size="small"
                  v-model="v.title"
                ></el-input>
                <el-button-group style="float: right; margin-right: 5px">
                  <el-button
                    class="item-add"
                    type="text"
                    icon="el-icon-plus"
                    size="small"
                    v-if="paperType == 1"
                    @click="handleAddQuestion(v)"
                    >添加试题</el-button
                  >
                  <el-popconfirm
                    confirm-button-text="删除"
                    cancel-button-text="取消"
                    icon="el-icon-info"
                    icon-color="red"
                    title="确定要删除吗？"
                    @confirm="handleCloseChapter(v)"
                  >
                    <el-button
                      slot="reference"
                      type="text"
                      size="small"
                      icon="el-icon-circle-close"
                      :disabled="testPaperChapterList.length == 1"
                      >删除</el-button
                    >
                  </el-popconfirm>
                </el-button-group>
              </div>
              <div class="chapter-item-des">
                <span class="item-txt">章节描述</span>
                <el-input
                  class="item-ipt"
                  size="small"
                  v-model="v.des"
                ></el-input>
                <el-input
                  v-if="paperType == 1"
                  placeholder="请输入分值"
                  v-model.number="v.batchScore"
                  size="small"
                  class="input-with-select"
                  style="width: 120px"
                >
                  <el-button
                    slot="append"
                    style="padding: 12px 6px"
                    @click="batchSetScore(i)"
                    >批量设置</el-button
                  >
                </el-input>
              </div>
              <div class="chapter-question">
                <draggable
                  class="draggable-wrap"
                  v-if="paperType == 1"
                  v-model="v.testSubjectVO"
                  handle=".question-title"
                >
                  <transition-group>
                    <div
                      class="draggable-item"
                      v-for="item in v.testSubjectVO"
                      :key="item.id"
                    >
                      <p
                        class="question-title sheng"
                        v-html="
                          item.testSubjects ? item.testSubjects.title : ''
                        "
                      >
                      </p>
                      <span class="score"
                        >分值
                        <el-input
                          class="order-ipt"
                          size="small"
                          v-model.number="item.score"
                        ></el-input
                      ></span>
                      <span
                        class="question-icon el-icon-view"
                        @click="handleLookQuestion(item)"
                      ></span>
                      <span
                        class="question-icon el-icon-close"
                        @click="handleDelQuestion(v, item)"
                      ></span>
                    </div>
                  </transition-group>
                </draggable>
                <ul v-if="paperType == 2">
                  <li>
                    <dl>
                      <dd>
                        <el-button
                          type="primary"
                          size="mini"
                          plain
                          icon="el-icon-plus"
                          @click="handleAddQuestionBank(v)"
                          >选择题库</el-button
                        >
                      </dd>
                      <dd style="width: 100px">
                        <QuestionTypeSelect
                          size="mini"
                          placeholder="选择题型"
                          :defaultValue="v.testSubjectVO[0].ruleVo.subjectType"
                          @emit="
                            (m) => (v.testSubjectVO[0].ruleVo.subjectType = m)
                          "
                        />
                      </dd>
                      <dd style="width: 100px">
                        <QuestionDifficultySelect
                          placeholder="选择难度"
                          size="mini"
                          :defaultValue="
                            v.testSubjectVO[0].ruleVo.subjectDifficulty
                          "
                          @emit="
                            (m) =>
                              (v.testSubjectVO[0].ruleVo.subjectDifficulty = m)
                          "
                        />
                      </dd>
                      <dd>
                        <span class="score" style="float: none; width: 130px"
                          >题目数量
                          <el-input
                            class="order-ipt"
                            size="mini"
                            v-model="v.testSubjectVO[0].ruleVo.subjectNum"
                            @input="
                              (n) =>
                                (v.testSubjectVO[0].ruleVo.subjectNum =
                                  parseInt(n))
                            "
                          ></el-input
                        ></span>
                      </dd>
                      <dd>
                        <span class="score" style="float: none; width: 130px"
                          >单题分值
                          <el-input
                            class="order-ipt"
                            size="mini"
                            v-model="v.testSubjectVO[0].ruleVo.score"
                          ></el-input></span
                      ></dd>
                    </dl>
                  </li>
                </ul>
                <div
                  class="question-bank-title"
                  v-if="
                    paperType == 2 &&
                    v.testSubjectVO[0].ruleVo.testQuestionBankList &&
                    v.testSubjectVO[0].ruleVo.testQuestionBankList.length
                  "
                >
                  已选题库：
                  <el-tag
                    :key="tag.id"
                    v-for="tag in v.testSubjectVO[0].ruleVo
                      .testQuestionBankList"
                    closable
                    size="small"
                    class="question-bank-title-tag"
                    disable-transitions
                    :type="tag.permission == 1 ? '' : 'success'"
                    @close="handleDelQuestionBank(v, tag)"
                  >
                    {{ tag.name }}
                  </el-tag>
                </div>
              </div>
            </div>
          </transition-group>
        </draggable>
      </div>
    </div>
    <QuestionSelect
      :defaultValue="selectedQuestion"
      @emit="setQusetionList"
      @notCheckedQuestion="notCheckedQuestion"
    />
    <QuestionBankSelect
      :defaultValue="selectedQuestionBank"
      @emit="setQusetionBankList"
    />
    <QuestionPreview />
  </div>
</template>
<script>
import { v4 as uuidv4 } from 'uuid'
import draggable from 'vuedraggable'
export default {
  components: {
    draggable,
    QuestionPreview: () => import('../public/QuestionPreview.vue'),
    QuestionSelect: () => import('../public/QuestionSelect.vue'),
    QuestionBankSelect: () => import('../public/QuestionBankSelect.vue'),
    QuestionTypeSelect: () => import('../public/QuestionTypeSelect.vue'),
    QuestionDifficultySelect: () =>
      import('../public/QuestionDifficultySelect.vue'),
  },
  data() {
    return {
      curMark: '',
      oldQuestion: [],
      testPaperChapterList: [],
      selectedQuestion: [], //已选试题
      selectedQuestionBank: [], //已选题库
    }
  },
  props: ['chapterList', 'paperType'],
  watch: {
    //试卷类型
    paperType: {
      immediate: true,
      handler(val) {
        this.init(val)
      },
    },
  },
  computed: {
    totalScore() {
      let score = 0
      if (this.paperType == 1) {
        this.testPaperChapterList.forEach((item) => {
          item.testSubjectVO.forEach((v) => {
            score = (parseFloat(score) + parseFloat(v.score)).toFixed(1)
          })
        })
      } else if (this.paperType == 2) {
        this.testPaperChapterList.forEach((item) => {
          item.testSubjectVO.forEach((v) => {
            score = (
              parseFloat(score) +
              parseFloat(v.ruleVo.score) * parseInt(v.ruleVo.subjectNum)
            ).toFixed(1)
          })
        })
      }
      return score == 'NaN' ? 0 : score
    },
  },
  mounted() {},
  methods: {
    //编辑|新增
    init(type) {
      if (this.chapterList.length) {
        this.testPaperChapterList = this.chapterList
        this.testPaperChapterList.forEach((v) => {
          this.$set(v, 'mark', uuidv4())
          this.$set(v, 'batchScore', 1)
        })
      } else {
        let initObj = this.initData(type)
        this.testPaperChapterList = [initObj]
      }
    },
    //初始化章节数据
    initData(type) {
      let initObj = {
        mark: uuidv4(),
        title: '', //章节名称
        des: '', //章节描述
        orderBy: 1, //排序
        paperId: '', //试卷id
        testSubjectVO: [], //试题集合{id，score,orderBy}/取值的规则
        batchScore: 1,
      }
      if (type == 2) {
        let obj = {
          ruleVo: {
            bankIds: [],
            score: 0,
            subjectDifficulty: '',
            subjectNum: 0,
            subjectType: '',
            testQuestionBankList: [],
          },
        }
        initObj.testSubjectVO.push(obj)
      }
      return initObj
    },
    //查看试题
    handleLookQuestion(row) {
      this.$bus.$emit('showDialogQuestionPreview', row)
    },
    //删除试题
    handleDelQuestion(row, item) {
      this.testPaperChapterList.forEach((m) => {
        if (m.mark == row.mark) {
          m.testSubjectVO = m.testSubjectVO.filter((n) => n.id != item.id)
        }
      })
    },
    //新增章节
    handleAddChapter() {
      let obj = this.initData(this.paperType)
      this.testPaperChapterList.push(obj)
    },
    //删除章节
    // QuestionBankChapter(row) {
    //   this.testPaperChapterList = this.testPaperChapterList.filter(
    //     (v) => v.mark != row.mark,
    //   )
    // },
    handleCloseChapter(row) {
      this.testPaperChapterList = this.testPaperChapterList.filter(
        (v) => v.mark != row.mark,
      )
    },
    //批量设置分数
    batchSetScore(idx) {
      let { testSubjectVO, batchScore } = this.testPaperChapterList[idx]
      if (batchScore <= 0) {
        this.warnMsg('分数必须大于0')
        return
      }
      if (!testSubjectVO.length) {
        this.warnMsg('请先添加试题')
        return
      }
      testSubjectVO.forEach((item) => {
        item.score = batchScore
      })
    },
    //添加试题 同一个试题在各章节只能添加一次
    handleAddQuestion(row) {
      this.curMark = row.mark
      this.selectedQuestion = []
      //当前章节试题id集合
      let curQuestion = row.testSubjectVO.map((v) => v.id)
      this.selectedQuestion = row.testSubjectVO.map((v) => v.id)
      //所有已选id集合
      this.testPaperChapterList.forEach((item) => {
        let ids = item.testSubjectVO.map((v) => v.id)
        this.selectedQuestion = [...this.selectedQuestion, ...ids]
      })
      //排除当前章节的试题id集合
      this.oldQuestion = this.selectedQuestion.filter(
        (v) => curQuestion.indexOf(v) == -1,
      )
      this.$bus.$emit('showDialogQuestionSelect')
    },
    //选择题库
    handleAddQuestionBank(row) {
      this.curMark = row.mark
      this.selectedQuestionBank = row.testSubjectVO[0].ruleVo.bankIds
      this.$bus.$emit('showDialogQuestionBankSelect')
    },
    //设置试题
    setQusetionList(row) {
      row = row.filter((v) => this.oldQuestion.indexOf(v.id) == -1)
      let testSubjectVO = []
      row.forEach((v, idx) => {
        let obj = {
          id: v.id,
          score: 1.0,
          orderBy: ++idx,
          ruleVo: {},
          testSubjects: v,
        }
        testSubjectVO.push(obj)
      })
      this.testPaperChapterList.forEach((v) => {
        if (v.mark == this.curMark) {
          v.testSubjectVO = testSubjectVO
        }
      })
    },
    //设置题库
    setQusetionBankList(row) {
      this.testPaperChapterList.forEach((v) => {
        if (v.mark == this.curMark) {
          let ruleVo = v.testSubjectVO[0].ruleVo
          ruleVo.bankIds = row.map((v) => v.id)
          ruleVo.testQuestionBankList = row
        }
      })
    },
    //删除已选题库
    handleDelQuestionBank(item, row) {
      let bankList = item.testSubjectVO[0].ruleVo.testQuestionBankList
      this.testPaperChapterList.forEach((v) => {
        if (v.mark == item.mark) {
          let ruleVo = v.testSubjectVO[0].ruleVo
          ruleVo.testQuestionBankList = bankList.filter((m) => m.id != row.id)
          ruleVo.bankIds = ruleVo.testQuestionBankList.map((m) => m.id)
        }
      })
    },
    //取消勾选的其他章节试题进行删除操作
    notCheckedQuestion(row) {
      let flag = this.oldQuestion.indexOf(row.id) != -1
      this.oldQuestion = this.oldQuestion.filter((v) => v != row.id)
      if (flag) {
        this.testPaperChapterList.forEach((item) => {
          item.testSubjectVO = item.testSubjectVO.filter((v) => v.id != row.id)
        })
      }
    },
  },
}
</script>
<style scoped lang="scss">
.tast-chapter {
  position: relative;
  .tast-score {
    margin-bottom: 20px;
    span {
      display: inline-block;
      width: 100px;
      padding-right: 12px;
      box-sizing: border-box;
      text-align: right;
      color: #606266;
    }
    p {
      display: inline;
      color: #666;
    }
  }
  .tast-chapter-wrap {
    position: relative;
  }
  .chapter-left {
    position: absolute;
    left: 0;
    top: 0;
    width: 100px;
    padding: 0 12px 0 0;
    box-sizing: border-box;
    p {
      font-size: 14px;
      color: #606266;
      line-height: 40px;
      text-align: right;
    }
  }
  .chapter-right {
    padding-left: 100px;
    min-height: 100px;
  }
  .chapter-item {
    margin: 10px 0;
    border: 1px solid #eee;
    .chapter-item-title {
      height: 33px;
      padding: 5px 10px;
      background: #409eff;
      cursor: move;
    }
    .item-txt {
      float: left;
      width: 80px;
      line-height: 32px;
      color: #fff;
    }
    .item-ipt {
      float: left;
      width: 550px;
      margin-right: 20px;
    }
    .item-add {
      margin-right: 10px;
    }
    .chapter-item-des {
      height: 33px;
      padding: 5px 10px;
      background: #f5f5f5;
      .item-txt {
        color: #333;
      }
    }
    .chapter-question {
      min-height: 60px;
      padding: 10px;
      box-sizing: border-box;
      ul {
        li {
          margin-bottom: 10px;
          height: 44px;
          line-height: 40px;
          box-sizing: border-box;
          padding: 0 10px;
          border-radius: 5px;
          background: #f5f5f5;
          border: 1px solid #eee;
          .order {
            float: left;
            width: 100px;
            .order-ipt {
              width: 60px;
            }
          }
          .question-title {
            float: left;
            width: 480px;
          }
          .score {
            float: left;
            width: 100px;
            .order-ipt {
              width: 60px;
            }
          }
          .question-icon {
            margin: 0 10px;
            font-size: 16px;
            color: #666;
            cursor: pointer;
            &:hover {
              color: var(--colorH1);
            }
          }
        }
        dl {
          dd {
            float: left;
            margin-right: 20px;
          }
        }
      }
      .question-bank-title {
        .question-bank-title-tag {
          margin-right: 10px;
        }
      }
    }
  }
}
.draggable-wrap {
  .draggable-item {
    margin-bottom: 10px;
    height: 44px;
    line-height: 40px;
    box-sizing: border-box;
    padding: 0 10px;
    border-radius: 5px;
    background: #f5f5f5;
    border: 1px solid #eee;
    .order {
      float: left;
      width: 100px;
      .order-ipt {
        width: 60px;
      }
    }
    .question-title {
      float: left;
      width: 580px;
      cursor: move;
    }
    .score {
      float: left;
      width: 100px;
      .order-ipt {
        width: 60px;
      }
    }
    .question-icon {
      margin: 0 10px;
      font-size: 16px;
      color: #666;
      cursor: pointer;
      &:hover {
        color: var(--colorH1);
      }
    }
  }
  .sortable-ghost,
  .sortable-chosen {
    background: #fdf6b9;
  }
}
.draggable-chapter {
  .sortable-ghost,
  .sortable-chosen {
    .chapter-item-title {
      background: #fdf6b9;
    }
  }
}
</style>
<style scoped>
.chapter-item-title >>> .el-button--text {
  color: #fff;
}
</style>